﻿using Microsoft.Extensions.DependencyInjection;
using Niaofei.Sdk;
using System.Reflection;

namespace Niaofei.Core
{
    public static class InjectionExtension
    {
        /// <summary>
        /// 添加服务
        /// </summary>
        public static void InjectionService(this IServiceCollection services, Assembly[] assemblies)
        {
            foreach (var assembly in assemblies)
            {
                var types = assembly.GetTypes();

                foreach (var type in types)
                {
                    services.AddServices(type);
                }
            }
        }

        private static void AddServices(this IServiceCollection services, Type type)
        {
            try
            {
                var injectionAttribute = type.GetCustomAttribute<InjectionAttribute>();

                if (injectionAttribute == null)
                {
                    return;
                }

                if (injectionAttribute.Type == null)
                {
                    services.Add(new ServiceDescriptor(type, type, injectionAttribute.ServiceLifetime));
                }
                else
                {
                    services.Add(new ServiceDescriptor(injectionAttribute.Type, type, injectionAttribute.ServiceLifetime));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}
